package com.yanhui.utils.sql;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//import com.yanhui.constant.Global;
//import com.yanhui.util.string._yhPropertiesUtils;



public class _dbUtils {


	private static  Connection conn;

	public static void main(String[] args) {
		//		_dbUtil db = new _dbUtil();
		//		System.out.println(db.getConnection());
		//		System.out.println("连接成功！");
		//		String name = "";
		//		List l = listDB(name);
		//		for(int i = 0;i<l.size();i++){
		//			System.out.println(l.get(i).toString());
		//		}
//		String a = getDatabaseName(url);
//		System.out.println(a);
	}

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public _dbUtils() {

	}

	/**
	 * 获取数据库的连接
	 * @return conn
	 */
	public static Connection getConnection(String url, String user, String pwd) {
		if(null == conn) {
			try {
				conn = DriverManager.getConnection(url, user, pwd);
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		return conn;
	}
	public static Connection getConnectionForDB(String databaseName, String user, String pwd) {
		if(null == conn) {
			try {
				conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/"+databaseName, user, pwd);
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		return conn;
	}
	
	/**
	 * 释放资源
	 * @param conn
	 * @param pstmt
	 * @param rs
	 */
	public static void closeResources(Connection conn,PreparedStatement pstmt,ResultSet rs) {
		if(null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} finally {
				if(null != pstmt) {
					try {
						pstmt.close();
					} catch (SQLException e) {
						e.printStackTrace();
						throw new RuntimeException(e);
					} finally {
						if(null != conn) {
							try {
								conn.close();
							} catch (SQLException e) {
								e.printStackTrace();
								throw new RuntimeException(e);
							}
						}
					}
				}
			}
		}
	}


	/**
	 * 列举数据库所有的表
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "static-access", "unchecked" })
	public static List listDB(String name, String url, String user, String pwd) {
		List list = new ArrayList();
		String sql = "show tables like '%"+name+"%';"; 							
		try {
			Connection conn = null; 							
			_dbUtils db = new _dbUtils();
			conn = db.getConnection(url, user, pwd);
			Statement stmt = conn.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY); 			
			ResultSet rs = stmt.executeQuery(sql); 				
			while(rs.next()){
				list.add(rs.getString(1));
			}
			return list;              							
		} catch (SQLException ex) {
			System.out.println(ex.getMessage());
			return null;
		}
	}

	/**
	 * 备份数据库
	 * @return
	 * @throws IOException 
	 */
	public static void exportDatatableTool(String datatableName, String url, String user, String pwd, String mysqlPath) throws IOException {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String filepath = "d:\\"+datatableName+sdf.format(date)+".sql";
		File file = new File("d:\\"+datatableName+sdf.format(date)+".sql");
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}  
		}
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("mysqldump" + " -u" + user + " -p" + pwd + " " + getDatabaseName(url) + " " + datatableName +"");
		Process process = Runtime.getRuntime().exec(mysqlPath+stringBuilder.toString());
		StringBuffer out1 = new StringBuffer();
		byte[] b = new byte[1024];
		for(int i;((i=process.getInputStream().read(b))!=-1);){
			out1.append(new String(b,0,i,"utf-8"));
		}
		String outStr = out1.toString();
		FileOutputStream fout = new FileOutputStream(filepath);
		OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
		writer.write(outStr);
		writer.flush();
		writer.close();
		fout.close();
	}

	public static String getDatabaseName(String url) {
		String result = url.substring(url.lastIndexOf("/")+1).replace("?characterEncoding=utf8&autoReconnect=true", "");
		return result;
	}
}
